/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.serc.pensieve.uicontroller;
import org.serc.pensieve.model.Admin;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;
import org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID;

/**
 *
 * @author Shani
 */
public class MainControler extends HttpServlet {

 
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
         HttpSession  ss = request.getSession();
       //  response.sendRedirect("Training.jsp");
        response.setContentType("text/html;charset=UTF-8");
       // System.out.println("hhhh");
         String act = request.getParameter("action");
         PrintWriter out = response.getWriter();


         //Getting Sessions
         String roleSession = "empty";
         if(act.equals("setLoginOneRole"))
         {

          //  String  tempId=(String)request.getParameter("userId");
              String  tempId=(String)request.getParameter("userId");
            int loginThisUsre_id=0 ;
            try {
             loginThisUsre_id = Integer.parseInt(tempId);
             ss.setAttribute("userID",loginThisUsre_id );
     
             } catch (Exception e) {

                 System.out.println(e.toString());
             }

              Admin obj=new Admin("1","1","1");
              ArrayList<String> qReceivedRegUsers = new ArrayList<String>();
              qReceivedRegUsers = obj.loginOne(loginThisUsre_id);
        //  int numOfRoles = ReceivedRegUsers.size()/2;
              //Set session only if previously sessions have'nt set properly.
              if((ss.getAttribute("userName")==null || ss.getAttribute("userPassword")==null || ss.getAttribute("userRole")==null))
              {
                  String aaa = qReceivedRegUsers.get(0);
                    ss.setAttribute("userName",qReceivedRegUsers.get(0));
                    ss.setAttribute("userPassword", qReceivedRegUsers.get(1));
                    ss.setAttribute("userRole", qReceivedRegUsers.get(2));



              if(qReceivedRegUsers.get(2).equals("Admin"))
              {
                  //UserRole userLogin = new Admin(qReceivedRegUsers.get(0), qReceivedRegUsers.get(1), qReceivedRegUsers.get(0));
                 // userLogin.login();
                 response.sendRedirect("index.jsp");


              }
              else if(qReceivedRegUsers.get(2).equals("Inspector"))
              {
                         response.sendRedirect("Training.jsp");

               }
               else
               {

                         response.sendRedirect("moderatorMain.jsp");

                }

              }
              else
              {
                  response.sendRedirect("login1.jsp?error=You have already logged in with"+ss.getAttribute("userRole")+" role.Please Log out and again log in and choose your desired role.");
              }
/*              if(qReceivedRegUsers.get(2).equals("Admin"))
              {
                         response.sendRedirect("index.jsp");


              }
              else if(qReceivedRegUsers.get(2).equals("Inspector"))
              {
                         response.sendRedirect("Training.jsp");

               }
               else
               {

                         response.sendRedirect("moderatorMain.jsp");
               
                }*/

         }
         else if(act.equals("Logout"))
         {

            ss.invalidate();
            response.sendRedirect("login1.jsp?errorMsg=Log out successFully!");
         }

         else if(act.equals("login"))
         {
            String username = null;
            String userpasword = null;

            username = request.getParameter("uname");
            userpasword = request.getParameter("upass");

            Admin obj=new Admin("1","1","1");
            ArrayList<String> ReceivedRegUsers = new ArrayList<String>();
            ReceivedRegUsers = obj.login(username,userpasword);
            int numOfRoles = ReceivedRegUsers.size()/2;
            System.out.println("num of roles are: "+numOfRoles);
            if(numOfRoles==0)
             {
             
                  response.sendRedirect("login1.jsp?error=Wrong UserName or Password!");
             }
             else if(numOfRoles==1)
             {
             //    HttpSession sessionSet = request.setSession("t",sdsd);
               //  Session setSession = new Sess
                 //As this user have only one role so directly redirect to requested page by setting its session.
                 ss.setAttribute("userID", ReceivedRegUsers.get(1));

               if(ReceivedRegUsers.get(0).equals("Admin"))
               {
                   //Setting Sessions
                   ss.setAttribute("userName",username);
                    ss.setAttribute("userPassword", userpasword);
                    ss.setAttribute("userRole", "Admin");
                     //redirect to Admin page and set session there.
                    response.sendRedirect("index.jsp");
               }
               else if(ReceivedRegUsers.get(0).equals("Inspector"))
               {
                   //Setting Sessions
                    ss.setAttribute("userName",username);
                    ss.setAttribute("userPassword", userpasword);
                    ss.setAttribute("userRole", "Inspector");
                    //redirect to Admin page and set session there.
                    response.sendRedirect("Training.jsp");

               }
               else if(ReceivedRegUsers.get(0).equals("Moderator"))
               {

                   //Setting Sessions
                    ss.setAttribute("userName",username);
                    ss.setAttribute("userPassword", userpasword);
                    ss.setAttribute("userRole", "Moderator");
                    //redirect to Admin page and set session there.
                    response.sendRedirect("moderatorMain.jsp");
               }
               else
               {
               //Redirect to Error page.
               }
               // response.sendRedirect("IntermidiateLoginPage.jsp?role1="+ReceivedRegUsers.get(0)+"&role2=&role3=");
             }
             else if(numOfRoles==2)
             {
                 response.sendRedirect("IntermidiateLoginPage.jsp?role1="+ReceivedRegUsers.get(0)+"&role2="+ReceivedRegUsers.get(2)+"&role3=&id1="+ReceivedRegUsers.get(1)+"&id2="+ReceivedRegUsers.get(3)+"&id3=");
             }
             else if(numOfRoles==3)
             {
                response.sendRedirect("IntermidiateLoginPage.jsp?role1="+ReceivedRegUsers.get(0)+"&role2="+ReceivedRegUsers.get(2)+"&role3="+ReceivedRegUsers.get(4)+"&id1="+ReceivedRegUsers.get(1)+"&id2="+ReceivedRegUsers.get(3)+"&id3="+ReceivedRegUsers.get(5));
             }

             //  System.out.println(check);
          /*  if(check)
            {
                response.sendRedirect("Training.jsp");
            }
            else
            {
                response.sendRedirect("login1.jsp");
            }
        */
        
        }
         
        //response.sendRedirect("Training.jsp");
//response.sendRedirect("Training.jsp");
        //HttpSession session = request.getSession();
      /* String command = request.getParameter("command");
response.sendRedirect("Training.jsp");
        //String player2 = (String) session.getAttribute("player2");
        if(command.equals("login"))
        {
            try{
            boolean check=obj.login(request);
          //  if(check)
            //{
                
               // out.println("shani");
           // }
            }
            catch(Exception ex){
                out.println(ex.getMessage());
            }
  //          response.sendRedirect("select.jsp");
        }*/


        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MainControler</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MainControler at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainControler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainControler.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MainControler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainControler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
